﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Interfaces;
using Microsoft.Win32;
using Path = System.IO.Path;

namespace ConverterApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        [ImportMany(typeof(ICsvFile))]
        private ICsvFile[] csvFiles;

        private ICsvFile currentFile;

        public MainWindow()
        {
            InitializeComponent();

            AggregateCatalog catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog("."));
            CompositionContainer container = new CompositionContainer(catalog);
            container.ComposeParts(this);
        }

        private void btnSelectInputCsvFilePath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog()
            {
                Filter = "Pliki CSV|*.csv|Wszystkie pliki|*.*"
            };
            if (dialog.ShowDialog(this) == true)
            {
                string path = dialog.FileName;
                txtInputCsvFilePath.Text = path;
            }
        }

        private void btnLoadInputCsvFile_Click(object sender, RoutedEventArgs e)
        {
            string path = txtInputCsvFilePath.Text;
            string fileName = System.IO.Path.GetFileName(path);
            string bankName = fileName.Substring(0, fileName.IndexOf("_"));
            currentFile = csvFiles.First(f => f.BankName == bankName);
            currentFile.ReadFromCsv(path);
            dgvTransactions.DataContext = currentFile.Transactions;
        }

        private void btnSelectOutputCsvFilePath_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog dialog = new SaveFileDialog()
            {
                Filter = "Pliki CSV|*.csv|Wszystkie pliki|*.*"
            };
            if (dialog.ShowDialog(this) == true)
            {
                string path = dialog.FileName;
                txtOutputCsvFilePath.Text = path;
            }
        }

        private void btnLoadOutputCsvFile_Click(object sender, RoutedEventArgs e)
        {
            currentFile.SaveToHomebankCsvFile(txtOutputCsvFilePath.Text);
            Process.Start("explorer.exe", "/select, " + txtOutputCsvFilePath.Text);
        }
    }
}
